// pages/rate/rate.js
const util = require('../../utils/util.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    salaryStart:['开始月份'],
    salaryEnd:['结束月份'],
    calDate:"",
    salaryBox: [1],
    salary:[],
    isReview:  false,
    isVerify:  false,
    // salaryStart: '开始月份',//默认起始时间  
    // salaryEnd: '结束月份',//默认结束时间 
    nowYear:"2025",
    // list:[{salaryStartdate:"开始月份",salaryEnddate:"结束月份",salary:""}],
    accSalary:"0.00",
    // salaryAfter:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  drawLine() {
    var context = wx.createCanvasContext('firstCanvas');
    context.setLineDash([5, 8],5);
    context.lineWidth = 10;
    context.strokeStyle = '#666';
    context.beginPath();
    context.moveTo(0, 0);
    context.lineTo(1040, 0);
    context.stroke();
    context.draw();
  },
  drawLine1() {
    var context = wx.createCanvasContext('secondCanvas');
    context.setLineDash([5, 8]);
    context.lineWidth = 10;
    context.strokeStyle = '#666';
    context.beginPath();
    context.moveTo(0, 0);
    context.lineTo(1040, 0);
    context.stroke();
    context.draw();
  },

  insert:function () { 
    var cb = this.data.salaryBox;
    
    // var index1 = this.data.index1;
    var salaryStart = this.data.salaryStart;
    var salaryEnd = this.data.salaryEnd
    var salay = this.data.salary;
    console.log(cb);
    cb.push(this.data.salaryBox.length);
   
    // index1.push(this.data.salaryBox.length);
    salaryStart.push('开始月份');
    salaryEnd.push("结束月份");
    salay.push('');
    // this.data.list.push({salaryStartdate:"开始月份",salaryEnddate:"结束月份",salary:""});
    this.setData({salaryBox: cb,salaryStart:salaryStart,salaryEnd:salaryEnd,salary:salay});
    },
    
  delBind:function () {  
    var cb = this.data.salaryBox;
    var salaryStart = this.data.salaryStart;
    var salaryEnd = this.data.salaryEnd;
    cb.pop();
    // index1.pop();
    salaryStart.pop();
    salaryEnd.pop();
    // this.data.list.push({salaryStartdate:"开始月份",salaryEnddate:"结束月份",salary:""});
    this.setData({salaryBox: cb,salaryStart:salaryStart,salaryEnd:salaryEnd});
  }, 

  bindDateChange(e) {
    var nowIdx = e.currentTarget.dataset.idx;//获取当前索引
    var val = e.detail.value;//获取输入的索引
    console.log(val);
    console.log(nowIdx)
    var oldVal = this.data.salaryStart;
    let that = this;
    oldVal[nowIdx]=val;//修改对应索引值的内容
    that.setData({
      salaryStart: oldVal
    });
    console.log("salaryStart数组");
    console.log(oldVal);
  },
  
  bindDateChange2(e) {
    var nowIdx = e.currentTarget.dataset.idx;//获取当前索引
    var val = e.detail.value;//获取输入的索引
    console.log(val);
    console.log(nowIdx)
    var oldVal = this.data.salaryEnd;
    let that = this;
    var salaryStart = this.data.salaryStart;
    if(salaryStart[nowIdx].indexOf("-") === -1){
      wx.showToast({
        title: '请先输入开始月份！',
        icon:'none'
      });
      return;
    }
    oldVal[nowIdx]=val;//修改对应索引值的内容
    that.setData({
      salaryEnd: oldVal
    });
    console.log("salaryEnd数组：");
    console.log(oldVal);
  },

getInputVal:function(e){
  var nowIdx=e.currentTarget.dataset.idx;//获取当前索引
  var value=e.detail.value;//获取输入的值
  if(/^(0|[1-9][0-9]*)$/.test(value) || /^([1-9][0-9]*\.)$/.test(value) || /^([1-9][0-9]*)+(\.[0-9]{1,2})?$/.test(value)){
    var temp1 = this.data.salary;
    temp1[nowIdx] = value;
    this.setData({salary:temp1});
  }else{
    wx.showToast({
      title: '请正确输入每月收入！\r\n(仅数字，最多2位小数)',
      icon:'none'
    });
    var temp1 = this.data.salary;
    temp1[nowIdx] = '';
    this.setData({salary:temp1});
  }
  console.log(this.data.salary);
},
/**
 * 
 * @param {String} dateStr1 
 * @param {String} dateStr2 
 */
compareDate:function(dateStr1,dateStr2){
  const date1 = new Date(dateStr1);
  const date2 = new Date(dateStr2);
  if (date1 > date2) {
      return 1;
  } else if (date1 < date2) {
      return 2;
  } else {
      return 0;
  }
},

/**
 * 
 * @param {String} salaryStartStr 
 * @param {String} salaryEndStr 
 */
calRentMonth:function(salaryStartStr,salaryEndStr){
  var salaryEnd = salaryEndStr;
  var salaryStart = salaryStartStr;
  var cal = this.data.calDate;
  var result = 0;
  // console.log(salaryEnd);
  // console.log(salaryStart);
  //传入其他字符串，直接返回0
  if(salaryEnd.indexOf("-") === -1 || salaryStart.indexOf("-") === -1){
    return 0;
  }
  var salaryStartComCal = this.compareDate(cal,salaryStart);
  var calComsalaryEnd = this.compareDate(cal,salaryEnd);
  // salaryStart <= cal < salaryEnd
  if(salaryStartComCal <= 1 && calComsalaryEnd === 2){
     if(salaryStart.slice(0,4) !== cal.slice(0,4)){
      result = Number(cal.slice(-2));
     }else{
      result = Number(cal.slice(-2)) - Number(salaryStart.slice(-2)) + 1;
     }
     return result;
    // salaryEnd 小于等于 cal的情况
  }else if(calComsalaryEnd <= 1)
  {
    // salaryEnd跨年，只能是往前面算
    if(salaryEnd.slice(0,4) !== cal.slice(0,4)){
      result = 0;
    }
    // salaryEnd不跨年
    else{
      // salaryStart跨年
      if(salaryStart.slice(0,4) !== cal.slice(0,4)){
         result = Number(salaryEnd.slice(-2));
      }
      // salaryStart不跨年
      else{
        result = Number(salaryEnd.slice(-2)) - Number(salaryStart.slice(-2)) + 1;
      }
    }
     return result;
  }
  else{
     result = 0;
  }
  return result;
},

/**
 * 
 */
calculateAccSalary:function(){
  var salaryStartArry = this.data.salaryStart;
  var salaryEndArray = this.data.salaryEnd;
  var salaryArray = this.data.salary;
  var head = '',tail = '',tagT = '1900-01',tagH = '1900-01';
  var sal = 0,total = 0;
  var month = 0;
  for(var i = 0;i < salaryStartArry.length;i++){
    if(salaryStartArry[i].indexOf("-") === -1 || salaryEndArray[i].indexOf("-") === -1){
      return -1.0
    }
    month = this.calRentMonth(salaryStartArry[i],salaryEndArray[i]);
    // console.log("month:"+month)
    if(month === 0){
      //month===0说明填写的时间区间不在本年度范围内，跳过
      continue;
    }else{
      tail = salaryEndArray[i],head = salaryStartArry[i];
      // console.log(this.compareDate(tail,tagH))
      if((this.compareDate(tail,tagH) === 2 || this.compareDate(tagT,head) === 2) && salaryArray[i] != ''){
        sal = Number(salaryArray[i]);
        total = total + sal * month;
        // console.log("total"+total)
      }else{
        //有时间区间重复，直接返回-1，提示用户重新填写。
        return -1.0
      }
    }
    tagH = salaryStartArry[i],tagT = salaryEndArray[i];
  }
  total = total.toFixed(2);
  this.setData({accSalary:total.toString()});
  return total;
},

calSalayAfter(){
  var salaryEnd = this.data.salaryEnd;
  var calDate = this.data.calDate;
  var salary = this.data.salary;
  var temp = 0,cal = Number(calDate.slice(-2));
  var findResult = false;
  for(var i = 0;i < salaryEnd.length;i++){
    temp = Number(salaryEnd[i].slice(-2));
    if(temp >= cal){
      findResult = true;
      break;
    }
  }
  if(findResult){
    return salary[i];
  }
  return "0.00"
},

clearAllStorage:function(){
  this.setData({
    salaryStart:['开始月份'],
    salaryEnd:['结束月份'],
    salaryBox: [1],
    salary:[]
  });
},

//确定的绑定事件函数
  onCompute(e){
    var result = this.calculateAccSalary();
    const salary = JSON.stringify(this.data.salary);
    const salaryEnd = JSON.stringify(this.data.salaryEnd);
    const salaryStart = JSON.stringify(this.data.salaryStart);
    const salaryBox = JSON.stringify(this.data.salaryBox);
    let that = this;
    if(result < 0){
      wx.showToast({
        title: '请正确填写！\r\n1.时间区间不能有重合\r\n2.未完整填写对应内容',
        icon:'none'
      });
      return;
    }
    // 仅需要计算的数据使用同步缓存。
    try {
      wx.setStorageSync("salary",salary);
      wx.setStorageSync("salaryEnd",salaryEnd);
      wx.setStorageSync("salaryStart",salaryStart);
      wx.setStorageSync("salaryBox",salaryBox);
    } catch (e) { 
      console.log(e);
    }
  
    let pages = getCurrentPages();//当前页面
    let prevPage = pages[pages.length - 2];
    prevPage.setData({
      salary:that.data.accSalary
    });
    wx.showToast({  
      title: '计算完成', // 提示的内容  
      icon: 'success', // 图标，成功时显示对号图标  
      duration: 3000, // 持续的时间，单位是毫秒  
      success: (res)=> {
        setTimeout(function(){
          wx.navigateBack({
            delta: 1  // 返回上一级页面。
          });
        }, 2000);
      }
    });
  },

  onLoad(options) {
    const mon = options.calDate;
    this.setData({calDate:mon});
    console.log(mon);
    const year = mon.split("-")
    this.setData({nowYear:year[0]});
    const that = this;
    try {
      var value = wx.getStorageSync('salary');
      if (value) {
        that.setData({salary:JSON.parse(value)});
      }
      value = wx.getStorageSync('salaryEnd');
      if (value) {
        that.setData({salaryEnd:JSON.parse(value)});
      }
      value = wx.getStorageSync('salaryStart');
      if (value) {
        console.log("salarystart解析"+JSON.parse(value))
        that.setData({salaryStart:JSON.parse(value)});
      }
      value = wx.getStorageSync('salaryBox');
      if (value) {
        that.setData({salaryBox:JSON.parse(value)});
      }
    } catch (e) {
      console.log(e)
    }
    // 页面显示前获取之前保存在本地的填写记录   
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.drawLine();
    this.drawLine1();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})